import { CheckAns } from "./CheckAns";

namespace LeetCode0503NextGreaterElements {

    function nextGreaterElements(nums: number[]): number[] {
        if (!nums) return [];
        const len: number = nums.length;    // array length
        let ans: number[] = (new Array(len)).fill(-1);  // init ans
        let stack: number[] = new Array();  // position records
        for (let i = 0; i < len * 2 - 1; i++) {
            const idx = i % len;    // array pos
            while (stack.length > 0 && nums[stack[stack.length - 1]] < nums[idx]) {
                //@ts-ignore
                ans[stack.pop()] = nums[idx];
            }
            stack.push(idx);
        }
        return ans;
    };

    // test
    const testData: { nums: number[], ans: number[] }[] = [
        { nums: [1, 2, 1], ans: [2, -1, 2] },
        { nums: [6, 2, 6, 5, 1, 2], ans: [-1, 6, -1, 6, 2, 6] }
    ];
    for (const data of testData) {
        const ans = nextGreaterElements(data.nums);
        CheckAns(data, ans);
    }

}